package com.android.lovely.ui.dialog

import android.Manifest
import android.app.Activity
import android.net.Uri
import android.os.Build
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.activityViewModels
import com.android.lovely.R
import com.android.lovely.databinding.DialogUserBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.ext.startImageCrop
import com.android.lovely.framework.BaseDialogFragment
import com.android.lovely.ui.activity.HomeActivity
import com.android.lovely.ui.viewmodel.LoginViewModel
import com.android.lovely.user.UserManager.registerAuthChange
import com.kotlin.extensions.context.ContextExt.startPageClearTask
import com.kotlin.extensions.view.ViewExt.clickable
import com.yalantis.ucrop.UCrop

/**
 *
 * @author why
 * @date 2025/3/9 17:08
 */
class UserDialog : BaseDialogFragment<DialogUserBinding>() {

    val viewModel by activityViewModels<LoginViewModel>()

    private val randomNames by lazy {
        // 从资源文件中获取随机名称列表
        resources.getStringArray(R.array.random_names).toList()
    }


    private var canCancel: Boolean = false
    private var uri: Uri? = null

    override fun initializeViews() {
        canCancel = arguments?.getBoolean("canCancel") ?: false
        registerAuthChange {
            binding.ivAvatar.loadWithPlaceholder(it.headImg, R.drawable.icon_default_avatar)
            binding.nickname.setText(it.name)
            binding.male.isSelected = it.gender == 1
            binding.female.isSelected = it.gender == 2
            binding.unknown.isSelected = it.gender != 1 && it.gender != 2
            checkEnable()
        }
        binding.nickname.doAfterTextChanged {
            checkEnable()
        }

        if (binding.nickname.text.isNullOrEmpty()) {
            setRandomNickname()
        }
        binding.ivRole.clickable {
            setRandomNickname()
        }
        binding.save.clickable {
            if (binding.nickname.text.isNullOrBlank()) {
                return@clickable
            }
            update()
        }
        binding.male.clickable {
            binding.male.isSelected = true
            binding.female.isSelected = false
            binding.unknown.isSelected = false
            checkEnable()
        }
        binding.female.clickable {
            binding.male.isSelected = false
            binding.female.isSelected = true
            binding.unknown.isSelected = false
            checkEnable()
        }
        binding.unknown.clickable {
            binding.male.isSelected = false
            binding.female.isSelected = false
            binding.unknown.isSelected = true
            checkEnable()
        }

        binding.ivAvatar.clickable {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                avatarSelectionLauncher.launch("image/*")
                return@clickable
            }
            storagePermissionRequestLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }

    private fun setRandomNickname() {
        binding.nickname.setText(randomNames.random())
    }

    private fun checkEnable() {
        binding.save.isEnabled = !binding.nickname.text.isNullOrBlank()
    }

    private fun update() {
        val currentName = binding.nickname.text.toString()
        val gender = when {
            binding.male.isSelected -> 1
            binding.female.isSelected -> 2
            binding.unknown.isSelected -> 0
            else -> 1 // 默认值，可根据实际情况调整
        }
        viewModel.updateUserInfo(currentName, gender, uri) {
            if (canCancel) {
                dismissAllowingStateLoss()
            } else {
                dismissAllowingStateLoss()
                activity?.startPageClearTask<HomeActivity>()
            }
        }
    }

    // 存储权限请求启动器
    private val storagePermissionRequestLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isPermissionGranted ->
        handleStoragePermissionRequestResult(isPermissionGranted)
    }

    // 裁剪活动启动器
    private val imageCropActivityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
        handleImageCropActivityResult(activityResult)
    }

    // 头像选择启动器
    private val avatarSelectionLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { selectedAvatarUri ->
        handleAvatarSelectionResult(selectedAvatarUri)
    }

    // 处理存储权限请求结果
    private fun handleStoragePermissionRequestResult(isPermissionGranted: Boolean) {
        if (isPermissionGranted) {
            startAvatarSelection()
        }
    }

    // 处理裁剪活动结果
    private fun handleImageCropActivityResult(activityResult: ActivityResult) {
        if (activityResult.resultCode == Activity.RESULT_OK) {
            val resultIntent = activityResult.data ?: return
            val croppedAvatarUri = UCrop.getOutput(resultIntent) ?: return
            updateAvatar(croppedAvatarUri)
        }
    }

    // 处理头像选择结果
    private fun handleAvatarSelectionResult(selectedAvatarUri: Uri?) {
        selectedAvatarUri?.let {
            startImageCrop(it)
        }
    }

    // 启动头像选择
    private fun startAvatarSelection() {
        avatarSelectionLauncher.launch("image/*")
    }

    // 启动图片裁剪
    private fun startImageCrop(avatarUri: Uri) {
        requireActivity().startImageCrop(imageCropActivityLauncher, avatarUri, isCircleCrop = true)
    }

    // 更新头像
    private fun updateAvatar(avatarUri: Uri) {
        // 这里可以添加更新头像的具体逻辑
        this.uri = avatarUri
        binding.ivAvatar.loadWithPlaceholder(avatarUri, R.drawable.icon_default_avatar)
    }

    override fun isBottom(): Boolean {
        return true
    }
}